package com.jcli.novel_p;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * 1.1.日志，记录操作，不完整版。
 */
public class WriteToPropertiesSwingUpdatedWithLog extends JFrame {
    private Properties properties;
    private int addedCount = 0;
    private DefaultTableModel tableModel;
    private JTable table;
    private Logger logger;
    private JTextArea logTextArea;

    public WriteToPropertiesSwingUpdatedWithLog() {
        properties = new Properties();

        try (InputStream inputStream = new FileInputStream("src/main/resources/config.properties")) {
            properties.load(new InputStreamReader(inputStream, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 配置日志记录器
        logger = Logger.getLogger("PropertyEditorLog");
        logger.setLevel(Level.INFO);
        try {
            FileHandler fileHandler = new FileHandler("property_editor.log", true);
            fileHandler.setFormatter(new SimpleFormatter());
            logger.addHandler(fileHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 创建Swing界面
        setTitle("配置属性编辑器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 400);
        setLayout(new BorderLayout());

        // 创建表格模型和表格
        tableModel = new DefaultTableModel();
        tableModel.addColumn("键");
        tableModel.addColumn("值");
        table = new JTable(tableModel);

        // 创建文本框和按钮
        JTextField keyTextField = new JTextField(20);
        JTextField valueTextField = new JTextField(20);
        JButton addButton = new JButton("添加属性");
        JButton deleteAllButton = new JButton("删除所有属性");

        // 创建面板以容纳文本框和按钮
        JPanel inputPanel = new JPanel();
        inputPanel.add(new JLabel("键:"));
        inputPanel.add(keyTextField);
        inputPanel.add(new JLabel("值:"));
        inputPanel.add(valueTextField);
        inputPanel.add(addButton);
        inputPanel.add(deleteAllButton);

        // 添加按钮的点击事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String key = keyTextField.getText().trim();
                String value = valueTextField.getText().trim();

                if (key.isEmpty() || value.isEmpty()) {
                    JOptionPane.showMessageDialog(WriteToPropertiesSwingUpdatedWithLog.this, "键和值不能为空。", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (properties.containsKey(key)) {
                    JOptionPane.showMessageDialog(WriteToPropertiesSwingUpdatedWithLog.this, "键 '" + key + "' 已存在，跳过该项。", "警告", JOptionPane.WARNING_MESSAGE);
                } else if (properties.containsValue(value)) {
                    Set<String> keys = properties.stringPropertyNames();
                    boolean valueExistsWithDifferentKey = false;

                    for (String existingKey : keys) {
                        if (properties.getProperty(existingKey).equals(value) && !existingKey.equals(key)) {
                            valueExistsWithDifferentKey = true;
                            break;
                        }
                    }

                    if (valueExistsWithDifferentKey) {
                        int option = JOptionPane.showConfirmDialog(WriteToPropertiesSwingUpdatedWithLog.this, "值 '" + value + "' 已存在，但键不同。是否录入已有的键值对？", "确认", JOptionPane.YES_NO_OPTION);
                        if (option == JOptionPane.YES_OPTION) {
                            properties.setProperty(key, value);
                            addedCount++;
                            JOptionPane.showMessageDialog(WriteToPropertiesSwingUpdatedWithLog.this, "键 '" + key + "' ='" + value + "' 已录入成功。", "提示", JOptionPane.INFORMATION_MESSAGE);
                            logUserAction("添加属性 - 键: " + key + ", 值: " + value);
                        } else {
                            JOptionPane.showMessageDialog(WriteToPropertiesSwingUpdatedWithLog.this, "已跳过键 '" + key + "' 的录入。", "提示", JOptionPane.INFORMATION_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(WriteToPropertiesSwingUpdatedWithLog.this, "值 '" + value + "' 已存在，但键相同，跳过该项。", "警告", JOptionPane.WARNING_MESSAGE);
                    }
                } else {
                    properties.setProperty(key, value);
                    addedCount++;
                    JOptionPane.showMessageDialog(WriteToPropertiesSwingUpdatedWithLog.this, "键 '" + key + "' ='" + value + "' 已录入成功。", "提示", JOptionPane.INFORMATION_MESSAGE);
                    logUserAction("添加属性 - 键: " + key + ", 值: " + value);
                }

                // 清空文本框
                keyTextField.setText("");
                valueTextField.setText("");

                // 将属性加载到表格模型中并刷新表格
                loadPropertiesToTableModel();
            }
        });

        // 添加删除所有按钮的点击事件监听器
        deleteAllButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int option = JOptionPane.showConfirmDialog(WriteToPropertiesSwingUpdatedWithLog.this, "确认删除所有属性吗？", "确认", JOptionPane.YES_NO_OPTION);
                if (option == JOptionPane.YES_OPTION) {
                    properties.clear();
                    addedCount = 0;
                    JOptionPane.showMessageDialog(WriteToPropertiesSwingUpdatedWithLog.this, "所有属性已被删除。", "提示", JOptionPane.INFORMATION_MESSAGE);
                    logUserAction("删除所有属性");
                }
                // 将属性加载到表格模型中并刷新表格
                loadPropertiesToTableModel();
            }
        });

        // 创建日志文本区域
        logTextArea = new JTextArea();
        logTextArea.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(logTextArea);

        // 添加表格到滚动窗格
        JScrollPane tableScrollPane = new JScrollPane(table);

        // 创建分页部分
        JPanel paginationPanel = createPaginationPanel();

        // 创建主面板以容纳表格、分页和日志文本区域
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(tableScrollPane, BorderLayout.CENTER);
        mainPanel.add(paginationPanel, BorderLayout.SOUTH);

        // 创建分割窗格以容纳主面板和日志文本区域
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mainPanel, logScrollPane);
        splitPane.setDividerLocation(250); // 设置分割窗格位置

        // 将组件添加到界面
        add(inputPanel, BorderLayout.NORTH);
        add(splitPane, BorderLayout.CENTER);

        // 显示初始的所有键值对
        setVisible(true);
    }

    private JPanel createPaginationPanel() {
        JPanel paginationPanel = new JPanel();
        paginationPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

        // 创建首页按钮
        JButton firstPageButton = new JButton("首页");
        firstPageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentPage = 1;
                loadPropertiesToTableModel();
            }
        });

        // 创建上一页按钮
        JButton prevPageButton = new JButton("上一页");
        prevPageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (currentPage > 1) {
                    currentPage--;
                    loadPropertiesToTableModel();
                }
            }
        });

        // 创建页数输入框和按钮
        JTextField currentPageTextField = new JTextField(3);
        currentPageTextField.setText(Integer.toString(currentPage));
        JButton goToPageButton = new JButton("跳转");
        goToPageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int requestedPage = Integer.parseInt(currentPageTextField.getText());
                    if (requestedPage >= 1 && requestedPage <= totalPage) {
                        currentPage = requestedPage;
                        loadPropertiesToTableModel();
                    } else {
                        JOptionPane.showMessageDialog(WriteToPropertiesSwingUpdatedWithLog.this, "无效的页数。", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(WriteToPropertiesSwingUpdatedWithLog.this, "无效的页数。", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 创建下一页按钮
        JButton nextPageButton = new JButton("下一页");
        nextPageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (currentPage < totalPage) {
                    currentPage++;
                    loadPropertiesToTableModel();
                }
            }
        });

        // 创建末页按钮
        JButton lastPageButton = new JButton("末页");
        lastPageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentPage = totalPage;
                loadPropertiesToTableModel();
            }
        });

        // 添加分页按钮到分页面板
        paginationPanel.add(firstPageButton);
        paginationPanel.add(prevPageButton);
        paginationPanel.add(currentPageTextField);
        paginationPanel.add(goToPageButton);
        paginationPanel.add(new JLabel(" / " + totalPage));
        paginationPanel.add(nextPageButton);
        paginationPanel.add(lastPageButton);

        return paginationPanel;
    }

    private void loadPropertiesToTableModel() {
        // 清空表格模型
        tableModel.setRowCount(0);

        int itemsPerPage = 20;
        int startIndex = (currentPage - 1) * itemsPerPage;
        int endIndex = Math.min(startIndex + itemsPerPage, properties.size());

        totalPage = (int) Math.ceil((double) properties.size() / itemsPerPage);

        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();

            if (startIndex <= 0 && endIndex > 0) {
                tableModel.addRow(new Object[]{key, value});
            } else {
                startIndex--;
                endIndex--;
            }
        }
    }

    private void logUserAction(String action) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = sdf.format(new Date());
        String logMessage = timestamp + " - 用户操作: " + action + "\n";
        logTextArea.append(logMessage);

        // 将日志信息写入日志文件
        logger.info(action);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new WriteToPropertiesSwingUpdatedWithLog();
            }
        });
    }

    private int currentPage = 1;
    private int totalPage = 1;
}
